package cn.edu.jxau.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.jxau.domain.PageBean;
import cn.edu.jxau.domain.post;
import cn.edu.jxau.service.queryPost;


/**
 * 这是一个对帖子排序的类
 * sort=1 按发帖时间排序
 * sort=2 按浏览量排序
 * sort=3 查询出浏览量前五的帖子
 * sort=4 查询出所有的加精的帖子
 * @author 刘勋承
 *
 */
public class postSortServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		String type=(String)request.getParameter("type");//获取帖子的类型
		String sort=request.getParameter("sort");
		
		queryPost queryPost = new queryPost();
		
		int pc = getPc(request);// 得到pc
		int ps = 5;// 给定ps的值，每页10行记录
		HttpSession session = request.getSession();
		PageBean<post> postList;
		if(sort.equals("1")){
			
			try {
				postList = queryPost.findAllByType(pc, ps, type);
				
				session.setAttribute("postlist", postList);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(sort.equals("2")){
			
			try {
				postList = queryPost.findAllByType1(pc, ps, type);
				
				session.setAttribute("postlist", postList);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(sort.equals("3")){
			
			try {
				postList = queryPost.findAllByType2(pc, ps, type);
				
				session.setAttribute("postlist", postList);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(sort.equals("4")){
			
			try {
				postList = queryPost.findAllByType3(pc, ps, type);
				session.setAttribute("postlist", postList);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		response.sendRedirect("topic.jsp");
	}
	private int getPc(HttpServletRequest req) {
		/*
		 * 1. 查看是否存在pc参数，如果存在，转换成int类型 2. 如果不存在pc参数，返回1
		 */
		String pc = req.getParameter("pc");
		if (pc != null && !pc.trim().isEmpty()) {
			return Integer.parseInt(pc);
		}
		return 1;
	}
}
